package com.sc.portal.controller;

import com.sc.common.pojo.SearchItem;
import com.sc.common.pojo.SearchResult;
import com.sc.portal.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @auther sc
 * @Date 2017/10/26
 */
@Controller
public class SearchController {

    @Autowired
    private SearchService searchService;

    @RequestMapping("/search")
    public String search(@RequestParam(value = "q") String keyword,
                         @RequestParam(value = "page",defaultValue = "1") int page,
                         @RequestParam(value = "rows",defaultValue = "60") int rows, Model m) throws UnsupportedEncodingException {

        keyword = new String(keyword.getBytes("ISO-8859-1"), "UTF-8");
        SearchResult searchResult =  searchService.search(keyword, page, rows);
        List<SearchItem> searchItemList = searchResult.getSearchItemList();
        for(SearchItem item:searchItemList){
            if(item.getImage()!=null&&item.getImage()!=""){
                String[] arrs = item.getImage().split(",");
                item.setImage(arrs[0]);
            }
        }
        m.addAttribute("query",keyword);
        m.addAttribute("totalPages",searchResult.getPageCount());
        m.addAttribute("itemList",searchItemList);
        m.addAttribute("page",searchResult.getCurrPage());
        return "search";
    }


}
